/*
 * @Author: Varandrew
 * @Date: 2018-02-05 11:43:30
 * @Last Modified by: cxl
 * @Last Modified time: 2019-07-01 15:24:25
 * -----------------------------------------------------
 * How to use
 * const oss = new Oss('<Your stsToken>', window)
 * oss.__init__()
 * After console tell ‘阿里云初始化成功’
 * oss.__main__('<path>', 'uploadImg', '<config>').then(res => func)
 * -----------------------------------------------------
 * uploadImg     config = {
 *                  file: < the object of your file>
 *                }
 * readImg       config = {
 *                 expires: 3600,
 *                 process: 'image/resize,m_fixed,w_100,h_100'
 *               }
 */

import md5 from 'js-md5'

const loadJs = Symbol('LoadOssJs')
const uploadImg = Symbol('UploadImage')
const readImg = Symbol('ReadImage')
const formatFileName = Symbol('FormatFileName')

export default class Oss {
  constructor(sts, window) {
    this.global = window
    this.document = this.global.document
    this.imageReg = /\.(png|jpe?g|gif|svg)(\?.*)?$/
    // ossClient
    this.client = undefined
    this.result = []
    // stsToken
    this.sts = sts
  }

  [loadJs](
    sid = 'js_aliyun_oss',
    url = 'https://gosspublic.alicdn.com/aliyun-oss-sdk-6.0.0.min.js',
    func
  ) {
    const dom = this.document.querySelector(`#${sid}`)
    if (!dom) {
      const script = this.document.createElement('script')
      script.src = url
      func && (script.onload = func)
      script.id = sid
      this.document.body.appendChild(script)
    }
  }

  [formatFileName](fileName) {
    // 获得文件名前缀
    function get_prefix(f) {
      return f.replace(/(.*\/)*([^.]+).*/gi, '$2')
    }

    // 获得文件名后缀
    function get_suffix(f) {
      return f.replace(/.+\./, '')
    }

    return [get_prefix(fileName), get_suffix(fileName)]
  }

  // 私有方法上传图片
  async [uploadImg](path, config) {
    const file = config.file
    if (!this.client || !file) return

    // 获取文件前缀和后缀
    const [fileName, fileType] = [...this[formatFileName](file.name)]
    const storeAs = `${path}${md5(fileName)}${+new Date()}.${fileType}`
    const result = await this.client
      .multipartUpload(storeAs, file)
      .then(res => {
        if (res.res.statusCode === 200) {
          return Promise.resolve(res)
        }
      })
      .catch(err => {
        return Promise.resolve(err)
      })
    return result
  }

  // 私有方法读取图片
  [readImg](path, config) {
    if (!this.client) {
      return
    }
    return this.client.signatureUrl(path, config)
  }

  __init__() {
    let timer = setInterval(() => {
      if (this.global.OSS) {
        // OSS Client init
        this.client = new this.global.OSS(this.sts)
        console.log('阿里云初始化完成')
        clearInterval(timer)
        timer = null
      } else {
        this[loadJs](undefined, undefined, () => {
          console.log('阿里云oss初始化中')
        })
      }
    }, 500)
  }

  __main__(path = 'Index/image/', method = 'uploadImg', config) {
    return method === 'uploadImg'
      ? this[uploadImg](path, config)
      : this[readImg](path, config)
  }
}
